package com.tengju.data.application.star;

import com.google.common.collect.Lists;
import com.tengju.data.domain.model.clickhouse.OdsBigdataStarIndicatorStatRepository;
import com.tengju.data.domain.model.user.StarIndicator;
import com.tengju.data.domain.model.user.UserIdCode;
import com.tengju.data.domain.shared.IdObject;
import com.tengju.user.domain.shared.CastUtil;
import com.tengju.user.domain.shared.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class StarIndicatorService {

    @Autowired
    OdsBigdataStarIndicatorStatRepository odsBigdataStarIndicatorStatRepository;

    public Map<UserIdCode,List<StarIndicator>> getNotReachIndicator(List<UserIdCode> idCodes) {

        List<Long> idCodeVal = idCodes.stream().map(IdObject::getValue).collect(Collectors.toList());

        List<StarIndicator> starIndicators = odsBigdataStarIndicatorStatRepository.batchQueryByIdCode(idCodeVal);

        //未达标指标
        List<StarIndicator> notReachList = starIndicators.stream()
                .filter(starIndicator -> !starIndicator.getIndicatorTargetValue().equals(new BigDecimal(-1)))
                .filter(starIndicator -> starIndicator.getIndicatorValue().compareTo(starIndicator.getIndicatorTargetValue()) < 0)
                .collect(Collectors.toList());
        //封装map
        HashMap<UserIdCode, List<StarIndicator>> notReachMap = new HashMap<>();
        for (StarIndicator starIndicator: notReachList) {

            UserIdCode idCode = new UserIdCode(starIndicator.getIdCode().getValue());
            List<StarIndicator> starIndicatorsList = notReachMap.get(idCode);

            if (CollectionUtils.isEmpty(starIndicatorsList)) {
                List<StarIndicator> starIndicatorList = new ArrayList<>();
                starIndicatorList.add(starIndicator);
                notReachMap.put(idCode,starIndicatorList);
            } else {
                starIndicatorsList.add(starIndicator);
            }

        }
        return notReachMap;
    }

    public List<StarIndicator> listStarIndicatorStat(UserIdCode idCode) {
        String dateStr = DateUtil.parseDateToString(DateUtil.DATE_FORMAT, new Date());
        int day = CastUtil.castInt(dateStr);
        return odsBigdataStarIndicatorStatRepository.batchQueryByIdCodeAndDate(idCode.getValue(), day);
    }

    public List<StarIndicator> listMaxDayStarIndicatorStat(UserIdCode idCode) {
        if (idCode == null) {
            return Lists.newArrayList();
        }
        return odsBigdataStarIndicatorStatRepository.batchQueryByIdCode(List.of(idCode.getValue()));
    }

}
